#pragma once
#include "Socket.hpp"
#include <iostream>
#include <unistd.h>
#include <signal.h>
#include <functional>
#include "Log.hpp"

Log lg;


using func_t = std::function<std::string(std::string &)>;

class TcpServer
{
public:
    TcpServer(const uint16_t port, func_t callback) : port_(port), callback_(callback)
    {
    }

    void InitServer()
    {
        sock_.Socket();
        sock_.Bind(port_);
        sock_.Listen();
        lg(Info, "TcpServer init success...");
    }

    void Start()
    {
        // 忽略异常信号
        signal(SIGCHLD, SIG_IGN);
        signal(SIGPIPE, SIG_IGN);

        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int sockfd = sock_.Accept(&clientip, &clientport);
            if (sockfd == -1)
            {
                continue;
            }

            if (fork() == 0)
            {
                // child
                if (fork() > 0)
                    exit(0);

                sock_.Close();
                // 孙子进程
                // 读取/发送数据
                // TODO
                std::string inbuffer_info;
                while (true)
                {
                    char buffer[1024];
                    int n = read(sockfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = 0;
                        inbuffer_info += buffer;
                        lg(Debug, "debug:\n%s", inbuffer_info.c_str());

                        // inbuffer_info可能收到多个报文，需要计算并发送
                        while (true)
                        {
                            std::string resp = callback_(inbuffer_info); // 每次会移除已经处理的报文

                            // 报文不完整
                            if (resp.empty())
                                break;

                            //lg(Debug, "debug:\nresponse:%s", resp.c_str());

                            write(sockfd, resp.c_str(), resp.size());
                        }
                    }
                    else if (n == 0)
                        break;
                    else if (n < 0)
                        break;
                }

                exit(0);
            }

            // 父进程关闭描述符
            close(sockfd);
        }
    }

    ~TcpServer()
    {
        sock_.Close();
    }

private:
    uint16_t port_;
    Sock sock_;
    func_t callback_; // 回调函数 执行Calculator
};